package com.jrx.anytxn.transaction.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.service.system.ITransactionCodeTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.*;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanMainInfoMapper;
import com.jrx.anytxn.transaction.service.ITlTransactionInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 交易信息service 实现
 *
 * @author : zhenghaopu
 * 2019/11/1
 */
@Service
public class TlTransactionInfoServiceImpl implements ITlTransactionInfoService {

    private static final Logger logger = LoggerFactory.getLogger(TlTransactionInfoServiceImpl.class);

    @Autowired
    private ITransactionCodeTableService transactionCodeTableService;

    @Autowired
    private ISegmentService segmentService;


    @Override
    public TlTransactionInfo buildTlTransactionInfo(TlDisbursementLog tlDisbursementLog, String reversalFlag) throws TxnBizException {

        //拷贝相同信息
        TlTransactionInfo tlTransactionInfo = BeanMapping.copy(tlDisbursementLog,TlTransactionInfo.class);
        tlTransactionInfo.setTxnCode(TransBizConstant.TXN_CODE_INSTSUM);//交易码
        tlTransactionInfo.setPostingAmount(tlDisbursementLog.getAmount());//入账金额
        tlTransactionInfo.setPostingDate(tlDisbursementLog.getBusinessDate());//入账日期
        //补充信息
        buildSimpleTlTransactionInfo(reversalFlag,tlTransactionInfo);

        return tlTransactionInfo;
    }

    @Override
    public TlTransactionInfo buildTlTransactionInfo(AmAccountMainInfo accountMainInfo, String reversalFlag) throws TxnBizException {

        //拷贝相同信息
        TlTransactionInfo tlTransactionInfo = BeanMapping.copy(accountMainInfo,TlTransactionInfo.class);

        //构建信息
        buildSimpleTlTransactionInfo(reversalFlag,tlTransactionInfo);
        return tlTransactionInfo;
    }

    @Override
    public TlTransactionInfo buildTlTransactionInfo(TlPaymentAllocationLog tlPaymentAllocationLog) throws TxnBizException {
        //拷贝相同信息
        TlTransactionInfo tlTransactionInfo = BeanMapping.copy(tlPaymentAllocationLog,TlTransactionInfo.class);
        tlTransactionInfo.setTxnCode(TransBizConstant.TXN_CODE_PAYMENT_DETAIL);//交易码
        tlTransactionInfo.setPostingAmount(tlPaymentAllocationLog.getPostingAmount());//入账金额
        tlTransactionInfo.setPostingDate(tlPaymentAllocationLog.getPostingDate());//入账日期
        //构建信息
        buildSimpleTlTransactionInfo(TransBizConstant.TRANSCATION_REVERSAL_FLAG_0,tlTransactionInfo);
        return tlTransactionInfo;
    }

    @Override
    public TlTransactionInfo buildTlTransactionInfo(TlTransactionInfo tlTransactionInfo, String txnCode,String reversalFlag) throws TxnBizException {
        TlTransactionInfo transactionInfo = BeanMapping.copy(tlTransactionInfo,TlTransactionInfo.class);
        transactionInfo.setOriginalTxnNumber(tlTransactionInfo.getTxnNumber());//原始交易参考号
        transactionInfo.setTxnCode(txnCode);
        transactionInfo.setTxnDescription(null);
        //构建信息
        buildSimpleTlTransactionInfo(reversalFlag,transactionInfo);
        //构建信息
        return transactionInfo;
    }

    /**
     * 生成退款交易流水
     * @param loanMainInfo 退款原订单
     * @param refundAmount 退款金额
     * @param businessDate 退款业务日期
     * @param seqNo 退款流水号
     * @return
     * @throws TxnBizException
     */
    @Override
    public TlTransactionInfo buildRefundTransInfo(AmLoanMainInfo loanMainInfo, BigDecimal refundAmount,Date businessDate,String seqNo) throws TxnBizException {
        TlTransactionInfo tlTransactionInfo = BeanMapping.copy(loanMainInfo,TlTransactionInfo.class);
        try {
            tlTransactionInfo.setId(segmentService.getId(TransBizConstant.TL_TRANSACTION_INFO_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlTransactionInfo.setTxnNumber(SeqUtils.getTxnNumber());//交易参考号
        tlTransactionInfo.setReversalFlag(TransBizConstant.TRANSCATION_REVERSAL_FLAG_0);//冲正标志
        String txnCode = TransBizConstant.TXN_CODE_REFUND;
        tlTransactionInfo.setPostingDate(businessDate);
        tlTransactionInfo.setPostingAmount(refundAmount);
        tlTransactionInfo.setSeqNo(seqNo);
        tlTransactionInfo.setTxnCode(txnCode);
        tlTransactionInfo.setTxnTime(new Date());//交易时间
        //获取交易描述
        String txnDes =
                transactionCodeTableService.findByCodeAndTenantId(txnCode,
                        tlTransactionInfo.getTenantId()).getChineseName();
        tlTransactionInfo.setTxnDescription(txnDes);//交易描述
        tlTransactionInfo.setCreateTime(null);
        tlTransactionInfo.setUpdateTime(null);
        tlTransactionInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);//操作员
        tlTransactionInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//版本号
        return tlTransactionInfo;
    }


    /**
     * 补充交易信息
     *
     * @param reversalFlag 冲正标志
     * @param tlTransactionInfo 交易信息
     * @throws TxnBizException 自定义异常
     */
    private void buildSimpleTlTransactionInfo(String reversalFlag, TlTransactionInfo tlTransactionInfo) throws TxnBizException {
        try {
            tlTransactionInfo.setId(segmentService.getId(TransBizConstant.TL_TRANSACTION_INFO_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlTransactionInfo.setTxnNumber(SeqUtils.getTxnNumber());//交易参考号
        tlTransactionInfo.setReversalFlag(reversalFlag);//冲正标志
        tlTransactionInfo.setTxnTime(new Date());//交易时间
        if(StringUtils.isBlank(tlTransactionInfo.getSeqNo())){
            tlTransactionInfo.setSeqNo("");//为空时设置空窜
        }
        if(StringUtils.isBlank(tlTransactionInfo.getLoanId())){
            tlTransactionInfo.setLoanId("");//为空时设置空窜
        }
        if(StringUtils.isBlank(tlTransactionInfo.getProductId())){
            tlTransactionInfo.setProductId("");//为空时设置空窜
        }
        if(StringUtils.isBlank(tlTransactionInfo.getTxnDescription())){
            //获取交易描述
            String txnDes =
                    transactionCodeTableService.findByCodeAndTenantId(tlTransactionInfo.getTxnCode(),
                            tlTransactionInfo.getTenantId()).getChineseName();
            tlTransactionInfo.setTxnDescription(txnDes);//交易描述
        }
        tlTransactionInfo.setCreateTime(null);
        tlTransactionInfo.setUpdateTime(null);
        tlTransactionInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);//操作员
        tlTransactionInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//版本号
    }

    /**
     * 根据订单信息生成交易流水信息
     *
     * @param amLoanMainInfo 订单信息
     * @param reversalFlag   冲正标志
     * @return 交易信息
     */
    @Override
    public TlTransactionInfo buildTlTransactionInfo(AmLoanMainInfo amLoanMainInfo, String reversalFlag) throws TxnBizException {

        TlTransactionInfo tlTransactionInfo = new TlTransactionInfo();
        tlTransactionInfo.setTenantId(amLoanMainInfo.getTenantId()); // 租户id
        tlTransactionInfo.setOrganizationId(amLoanMainInfo.getOrganizationId()); // 机构id
        tlTransactionInfo.setChannel(amLoanMainInfo.getChannel()); // 渠道
        tlTransactionInfo.setCustomerId(amLoanMainInfo.getCustomerId()); // 客户id
        tlTransactionInfo.setSeqNo(amLoanMainInfo.getSerialNumber()); // 流水号
        tlTransactionInfo.setLoanId(amLoanMainInfo.getLoanId()); // 贷款订单id
        tlTransactionInfo.setProductId(amLoanMainInfo.getProductId()); // 产品id
        tlTransactionInfo.setTxnCode(TransBizConstant.TXN_CODE_INSTSUM);//交易码
        tlTransactionInfo.setPostingAmount(amLoanMainInfo.getLoanAmount());//入账金额
        tlTransactionInfo.setPostingDate(amLoanMainInfo.getPostingDate());//入账日期
        tlTransactionInfo.setSubChannel(amLoanMainInfo.getSubChannel());
        tlTransactionInfo.setThirdChannel(amLoanMainInfo.getThirdChannel());
        //补充信息
        buildSimpleTlTransactionInfo(reversalFlag,tlTransactionInfo);

        return tlTransactionInfo;
    }
}
